<?php


namespace Beerus\Modules\Album\Controllers;

use hhz\constant\redis\redisKeys;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\album\AlbumRecommendCache;
use Biz\model\Album\AlbumListModel;
use Biz\service\Album\AlbumListService;
use Biz\service\Album\AlbumRecommendService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Hhz\Redis\newCache;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AlbumRecommendController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        // 处理查询条件
        $list = AlbumRecommendService::list();
        $total = $list['total'];
        $list = $list['list'] ?? [];
        $gridModel = new pGridDataModel($list, $total, ['perPage' => self::PAGE_SIZE]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->tools(function ($tool) {
                $url = "/admin/album/recommend/create";
                $tool->append('<a class="btn btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'更新推荐清单\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'500px\', \'600px\'],
                                content: \''.$url.'\'
                            });
               ">更新推荐清单</a>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
            });
            $grid->column('album_id', '好物清单id');
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('cover_img', '封面图')->display(function ($coverImg) {
                return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'800px\'],content: \''.$coverImg.'\'});">
                                <img width="100px" height="100px" src="'.$coverImg.'">
                            </a>';
            });
            $grid->column('title', '好物清单标题');
            $grid->column('tags', '标签');
            $grid->column('desc', '清单描述');
            $grid->column('status', '状态');
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();

        });

        return $content->header("发现好物 | 推荐清单管理")->row($grid);

    }

    public function create(Request $request, \App\Admin\Extensions\WorkContent $content)
    {

        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 20);
SCRIPT;
            Admin::script($script);
        }

        $key = redisKeys::KEY_B_CACHE_ALBUM_RECOMMEND_OFFICIAL_LIST;
        $redis = new newCache($key);
        $aData = $redis->getCache();
        $info['album_id'] =$aData ? explode(',', $aData):[];

//        $info['album_id'] = AlbumRecommendCache::getData();
        $form = new Form($info);
        $form->hidden('id');
        $form->list('album_id', '清单id')->required();
        $form->confirm('确定更新吗？', 'add');
        $form->action(route('album_recommend.save'));
        $title = '更新推荐清单';

        return $content->header($title)
            ->row($form);
    }

    public function save(Request $request)
    {
        $params = $request->all();
        try {
            $data = $params['album_id']['values'] ?? '';
            if ($data) {
                $albumIds = array_slice(array_unique($data), 0, 6);
                //查询状态是否是已审核通过
                $dataMap = AlbumListService::getAlbumListByIds($albumIds , ['status' => AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP]);
                foreach ($albumIds as $albumId){
                    if(!isset($dataMap[$albumId])){
                        throw new \Exception('清单id:'.$albumId.'不存在 或 状态异常 请更换');
                    }
                }
                if(!$albumIds || count($albumIds) <6){
                    throw new \Exception('推荐清单 至少添加6个');
                }
                $data = implode(',',$albumIds);
                $key = redisKeys::KEY_B_CACHE_ALBUM_RECOMMEND_OFFICIAL_LIST;
                $redis = new newCache($key);
                $redis->setCache($data);
//                AlbumRecommendCache::addData($data);
            }
            $success = new MessageBag([
                'title' => '保存成功',
            ]);

            return redirect('/admin/album/recommend/create?code=1')->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,'.$e->getMessage(),
            ]);

            return back()->withInput()->with(compact('error'));
        }
    }

}
